'use client';

import { useState, useEffect } from 'react';
import { EnvType, ENV_CONFIG } from '@/utils/env';
import { WechatService } from '@/services/wechat';

// 使用单例模式获取实例
const wechatService = WechatService.getInstance();

export default function Home() {
  const [qrcodes, setQrcodes] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);
  }, []);

  const generateAllQRCodes = async () => {
    try {
      setLoading(true);
      setError(null);

      const environments: Array<keyof EnvType> = ['v1', 'v5', 'test'];
      const results: Record<string, string> = {};

      for (const env of environments) {
        const qrcodeUrl = await wechatService.getQRCode({
          path: 'pages/index/index',
          env,
          type: 'trial',
        });
        results[env] = qrcodeUrl;
      }

      setQrcodes(results);
    } catch (error: unknown) {
      console.error('Error details:', error);
      const errorMessage = error instanceof Error ? error.message : '生成二维码失败';
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  if (!isClient) {
    return (
      <main className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 p-8">
        <div className="max-w-5xl mx-auto bg-slate-800/50 rounded-2xl shadow-xl p-8 border border-slate-700">
          {/* 简单的加载状态 */}
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 p-8">
      <div className="max-w-5xl mx-auto bg-slate-800/50 rounded-2xl shadow-xl p-8 border border-slate-700">
        <h1 className="text-4xl font-bold mb-12 text-center text-white">车帮帮小程序</h1>

        <div className="space-y-8">
          <div className="bg-slate-800/80 border border-slate-700 rounded-xl p-6">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-center space-y-4 sm:space-y-0 sm:space-x-12">
              <p className="text-slate-300 flex items-center">
                <span className="w-28 inline-block font-medium text-slate-400">页面路径：</span>
                <span className="text-white font-mono bg-slate-700/50 px-3 py-1 rounded-lg">/pages/index/index</span>
              </p>
              <p className="text-slate-300 flex items-center">
                <span className="w-28 inline-block font-medium text-slate-400">小程序：</span>
                <span className="text-white font-mono bg-slate-700/50 px-3 py-1 rounded-lg">体验版</span>
              </p>
            </div>
          </div>

          <div className="text-center">
            <button
              onClick={generateAllQRCodes}
              className={`
                px-8 py-3 bg-indigo-600 hover:bg-indigo-700
                text-white rounded-lg
                font-medium transition-colors
                focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-slate-900
                ${loading ? 'opacity-50 cursor-not-allowed' : ''}
              `}
              disabled={loading}
            >
              {loading ? (
                <span className="flex items-center justify-center">
                  <svg
                    className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    />
                  </svg>
                  生成中...
                </span>
              ) : (
                '生成所有环境小程序码'
              )}
            </button>
          </div>

          {error && (
            <div className="mt-6 p-4 bg-red-900/20 border border-red-800 rounded-lg">
              <p className="text-red-400 flex items-center">
                <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fillRule="evenodd"
                    d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                    clipRule="evenodd"
                  />
                </svg>
                {error}
              </p>
            </div>
          )}

          {Object.keys(qrcodes).length > 0 && !error && (
            <div className="qr-code-flex mt-8">
              {(['v5', 'v1', 'test'] as const).map((env) => (
                <div
                  key={env}
                  className="
                    bg-slate-800/80 rounded-xl p-6
                    border border-slate-700
                    transition-colors
                    hover:border-indigo-500/50
                    flex flex-col items-center
                    w-full sm:w-auto
                  "
                >
                  <div className="text-sm font-medium mb-4 px-4 py-1.5 bg-slate-700/50 text-slate-300 rounded-full">
                    {env.toUpperCase()} 环境 - 体验
                  </div>
                  <div className="p-2 bg-white rounded-lg">
                    <img src={qrcodes[env]} alt={`${env.toUpperCase()} QR Code`} className="max-w-[180px] rounded-lg" />
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
